<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "user_product".
 *
 * @property integer $id
 * @property integer $product_id
 * @property integer $user_id
 * @property double $num
 * @property double $buy_price
 * @property double $sale_price
 * @property string $create_at
 * @property string $update_at
 *
 * @property Product $product
 * @property User $user
 */
class UserProduct extends \app\models\BaseModel {
    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'user_product';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['product_id', 'user_id', 'num', 'buy_price', 'sale_price'], 'required'],
            [['product_id', 'user_id'], 'integer'],
            [['num', 'buy_price', 'sale_price'], 'number'],
            [['create_at', 'update_at'], 'safe'],
            [['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'id']],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'product_id' => 'Product ID',
            'user_id' => 'User ID',
            'num' => 'Num',
            'buy_price' => 'Buy Price',
            'sale_price' => 'Sale Price',
            'create_at' => '创建时间',
            'update_at' => '更新时间',
        ];
    }

    public function fields() {
        $fields = [
            'id',
            'product',
            'user',
            'num',
            'buy_price',
            'sale_price',
        ];
        $fields = array_combine($fields, $fields);

        return $fields;
    }

    public function extraFields() {
        $fields = [
            'product_id',
            'user_id',
            'create_at',
            'update_at',
        ];
        $fields = array_combine($fields, $fields);
        return $fields;
    }

    public static function getByProduct(Product $product, User $user) {
        $model = static::findOne([
            'user_id'=>$user->id,
            'product_id'=>$product->id,
        ]);
        if(!$model) {
            $model = new static();
            $model->user_id = $user->id;
            $model->product_id = $product->id;
            $model->num = 0;
            $model->buy_price = 0;
            $model->sale_price = 0;
        }
        return $model;
    }

    public function getProduct() {
        return $this->hasOne(Product::className(), ['id' => 'product_id'])->inverseOf('userProducts');
    }

    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'user_id'])->inverseOf('userProducts');
    }
}
